import 'package:flutter/material.dart';
import 'package:ichinesereader/controller/user.dart';
import 'package:ichinesereader/models/forms/forms.dart';
import 'package:ichinesereader/models/parent/miniProfile.dart';
import 'package:ichinesereader/models/student/ProfileStudent.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/layouts/customAppBar.dart';
import 'package:intl/intl.dart';
import 'package:reactive_forms/reactive_forms.dart';
import 'package:reactive_segmented_control/reactive_segmented_control.dart';
import 'package:get/get.dart';

// ignore: must_be_immutable
class StudentProfileSettingsForParent extends StatelessWidget {
  StudentProfileSettingsForParent({
    Key? key,
    required this.studentItem,
  }) : super(key: key);

  ProfileStudent studentItem;

  @override
  Widget build(BuildContext context) {
    Log.debug('build StudentProfileSettingsForParent');
    final UserController _userController = Get.find();

    Log.debug(
        "build StudentProfileSettingsForParent studentId=${studentItem.userId.toString()}");

    FormGroup form;
    StudentDetailsParentEditFormModel editFormModel =
        StudentDetailsParentEditFormModel();
    form = editFormModel.form;
    var dateformat = new DateFormat('MM/dd/yyyy');

    void _onUpdate() {
      MiniProfile dto = new MiniProfile();
      dto.email = form.control('email').value;
      if (form.control('dateofbirth').value != null)
        dto.birthday = dateformat.format(form.control('dateofbirth').value);
      dto.firstName = form.control('firstname').value;
      dto.lastName = form.control('lastname').value;
      dto.gender = form.control('gender').value;
      _userController
          .updateChild(studentItem.userName!, dto)
          .then((statusMessage) {
        if (statusMessage.status == 1000) {
          Get.snackbar('Message'.tr, 'Successfully updated'.tr,
              backgroundColor: Theme.of(context).primaryColor,
              colorText: Theme.of(context).primaryColorLight,
              snackPosition: SnackPosition.BOTTOM);
          Get.offAndToNamed("/parent/home");
        } else {
          Get.snackbar('Message'.tr, 'Error to update student'.tr,
              backgroundColor: Theme.of(context).primaryColor,
              colorText: Theme.of(context).primaryColorLight,
              snackPosition: SnackPosition.BOTTOM);
        }
      });
    }

    List<Widget> _buildObxForm() {
      return <Widget>[
        ReactiveTextField(
          formControlName: 'firstname',
          style: Theme.of(context).textTheme.titleSmall,
          decoration: InputDecoration(
            labelText: '*First Name'.tr,
          ),
          maxLength: 150,
        ),
        SizedBox(
          height: 12,
        ),
        ReactiveTextField(
          formControlName: 'lastname',
          style: Theme.of(context).textTheme.titleSmall,
          decoration: InputDecoration(
            labelText: '*Last Name'.tr,
          ),
          maxLength: 150,
        ),
        SizedBox(
          height: 12,
        ),
        ReactiveTextField(
          formControlName: 'email',
          style: Theme.of(context).textTheme.titleSmall,
          decoration: InputDecoration(
            labelText: 'Email'.tr,
          ),
        ),
        SizedBox(
          height: 12,
        ),
        ReactiveTextField<DateTime>(
          formControlName: 'dateofbirth',
          readOnly: true,
          decoration: InputDecoration(
            labelText: 'Date of Birth'.tr,
            suffixIcon: ReactiveDatePicker<DateTime>(
              formControlName: 'dateofbirth',
              firstDate: DateTime(1990),
              lastDate: DateTime(2030),
              builder: (context, picker, child) {
                return IconButton(
                  onPressed: picker.showPicker,
                  icon: const Icon(Icons.date_range),
                );
              },
            ),
          ),
        ),
        SizedBox(
          height: 12,
        ),
        ReactiveSegmentedControl<String, String>(
          formControlName: 'gender',
          decoration: InputDecoration(
            labelText: 'Gender'.tr,
            border: OutlineInputBorder(),
            helperText: '',
          ),
          unselectedColor: Get.theme.primaryColorLight,
          padding: const EdgeInsets.all(0),
          children: {
            'male': Text('Male'.tr,
                style: TextStyle(
                  color: Color(0xff00599b),
                  fontSize: 16.0,
                  letterSpacing: 1.0,
                )),
            'female': Text('Female'.tr,
                style: TextStyle(
                  color: Color(0xff00599b),
                  fontSize: 16.0,
                  letterSpacing: 1.0,
                )),
          },
        ),
        SizedBox(height: 12.0),
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            ReactiveFormConsumer(
              builder: (context, form, child) {
                return ElevatedButton(
                    child: Text(
                      'Update'.tr,
                      style: TextStyle(
                        color: Color(0xffd8ffff),
                        letterSpacing: 1.0,
                      ),
                    ),
                    onPressed: _onUpdate);
              },
            ),
          ],
        ),
      ];
    }

    form.control('firstname').value = studentItem.firstName;
    form.control('lastname').value = studentItem.lastName;
    form.control('email').value = studentItem.email;
    if (studentItem.dateOfBirth != null)
      form.control('dateofbirth').value =
          dateformat.parse(studentItem.dateOfBirth.toString());
    form.control('gender').value = studentItem.gender ?? 'male';

    return Scaffold(
        backgroundColor: Colors.transparent,
        appBar: CustomAppBar(title: 'Edit Student'.tr),
        body: Container(
          padding: EdgeInsets.all(60),
          decoration: BoxDecoration(
            color:
                Get.isDarkMode ? Colors.black.withOpacity(0.1) : Colors.white,
          ),
          child: SingleChildScrollView(
            primary: false,
            child: Padding(
              padding: const EdgeInsets.fromLTRB(36, 18, 36, 18),
              child: ReactiveForm(
                formGroup: form,
                child: Column(
                  children: _buildObxForm(),
                ),
              ),
            ),
          ),
        ));
  }
}
